#!/usr/bin/env python
import sys
from string import Template
from xml.etree.ElementTree import parse

indent_unit = '    '

def load_template_from_file(templatefile):
    tmpl_file = open(templatefile, 'r')
    return Template(''.join(tmpl_file.readlines()))

def find_main_window(root):
    widgets = root.getiterator('widget')
    for widget in widgets:
        if widget.attrib['class'] == 'GtkWindow':
            return widget
    return None

def get_widget_init(widget_node):
    try:
        widget_class = widget_node.attrib['class']
        widget_id = widget_node.attrib['id']
    except:
        return ''

    simple_widgets = ('GtkToggleButton', 'GtkSpinButton', 'GtkCheckButton',
                      'GtkComboBoxEntry', 'GtkProgressBar', 'GtkStatusBar',
                      'GtkRadioButton', 'GtkEntry', 'GtkComboBox')
    if widget_class in simple_widgets:
        indent = indent_unit * 2
        tmpl = Template(indent + "self.$widget_id = self.widget_tree.get_widget('$widget_id')\n")
    elif widget_class == 'GtkTextView':
        tmpl = load_template_from_file('textview_tmpl.py')
    elif widget_class == 'GtkTreeView':
        tmpl = load_template_from_file('treeview_tmpl.py')
    else:
        return ''

    return tmpl.substitute(widget_id=widget_id)

def get_callback(signal_node):
    tmpl = Template(indent_unit + \
                    'def $callback_name(self, widget${callback_arguments}):\n' + \
                    (indent_unit * 2) + "print '$callback_name called'\n")
    return tmpl.substitute(callback_name=signal_node.attrib['handler'], callback_arguments='')


def main():
    if len(sys.argv) < 2:
        print "Usage: %s ui_file.glade" % sys.argv[0]
        sys.exit(1)

    gladefile = sys.argv[1]
    tree = parse(gladefile)
    root = tree.getroot()
    app_tmpl = load_template_from_file('app_tmpl.py')

    win_node = find_main_window(root)
    widgets = [get_widget_init(wnode) for wnode in win_node.getiterator('widget')]
    callbacks = [get_callback(snode) for snode in root.getiterator('signal')]
    print app_tmpl.substitute(gladefile=gladefile,
                              main_window_name=win_node.attrib['id'],
                              widgets=''.join(widgets),
                              callbacks='\n'.join(callbacks))


if __name__ == '__main__':
    main()

